package com.qjj.studydainty.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.qjj.studydainty.Db.DbUtil;
import com.qjj.studydainty.DownloadThread;
import com.qjj.studydainty.R;
import com.qjj.studydainty.entity.History;
import com.qjj.studydainty.entity.MyApplication;

import java.io.File;
import java.util.Objects;

import static com.qjj.studydainty.activity.MainActivity.currentTitle;
import static com.qjj.studydainty.activity.MainActivity.currentUrl;
import static com.qjj.studydainty.activity.MainActivity.mainPageUrl;
import static com.qjj.studydainty.entity.MyApplication.ERROR_WEBVIEW;
import static com.qjj.studydainty.entity.MyApplication.FILE_LENGTH;
import static com.qjj.studydainty.entity.MyApplication.handler;
import static com.qjj.studydainty.entity.MyApplication.APP_CACHE_DIRNAME;
import static com.qjj.studydainty.entity.MyApplication.nightCode;
import static com.qjj.studydainty.util.Util.getFileName;

public class WebViewFragment extends Fragment {

    private WebView webView = null;
    private FrameLayout frameLayout = null;
    private ProgressBar progressBar = null;

    //手势相关
    private float posx;
    private float posy;
    private float curposx;
    private float curPosy;

    private String startUrl;

    public WebViewFragment() {
    }

    public WebViewFragment(String startUrl) {
        this.startUrl = startUrl;
    }

    public WebView getWebView() {
        return webView;
    }

    public FrameLayout getFrameLayout() {
        return frameLayout;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.webview_fragment, container, false);
        webView = view.findViewById(R.id.webview);
        progressBar = view.findViewById(R.id.progressBar);
        frameLayout = view.findViewById(R.id.framelayout);

        setWebview();
        setWebViewListener();

        loadUrl();


        return view;
    }

    private void loadUrl() {
        webView.loadUrl(startUrl == null ? mainPageUrl : startUrl);
    }

    //配置webView
    @SuppressLint("SetJavaScriptEnabled")
    private void setWebview() {

        WebSettings webSettings = webView.getSettings();
        //启用js
        webSettings.setJavaScriptEnabled(true);
        //当界面含有http和httpS两种类型图片时，解决部分图片不显示
        webSettings.setBlockNetworkImage(false);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);

        //设置缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        // 开启database storage API功能
        webSettings.setDatabaseEnabled(true);
        //解决部分图片不加载
        //配置安全源站尝试从不安全源站加载资源时WebView的行为
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        String cacheDirPath = Objects.requireNonNull(getContext()).getFilesDir().getAbsolutePath() + APP_CACHE_DIRNAME;
        File file = new File(cacheDirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        webSettings.setAppCacheEnabled(true);
        // 设置数据库缓存路径
        webSettings.setAppCachePath(cacheDirPath);

        webSettings.setSupportMultipleWindows(false);

        //WebView.setWebContentsDebuggingEnabled(true);
        //webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // webSettings.setUseWideViewPort(true);//宽屏


        //webSettings.setSupportZoom(true);//支持缩放

        //webSettings.setSupportMultipleWindows(true);

       /* setJavaScriptEnabled(true) ;//支持js脚本

        setUserWideViewPort(false) ;//将图片调整到适合webview的大小

        setLayoutAlgorithm(LayoutAlgrithm.SINGLE_COLUMN) ;//支持内容从新布局
        supportMultipleWindows() ;//多窗口
        setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK) ;//关闭webview中缓存

        setNeedInitialFocus(true) ;//当webview调用requestFocus时为webview设置节点
        setjavaScriptCanOpenWindowsAutomatically(true) ;//支持通过JS打开新窗口
        setLoadsImagesAutomatically(true) ;//支持自动加载图片
        setBuiltInZoomControls(true);//支持缩放

        webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);//设置滚动条隐藏
        webView.getSettings().setGeolocationEnabled(true);//启用地理定位
        //webView.getSettings().setRenderPriority(RenderPriority.HIGH);//设置渲染优先级*/

        //webView.setInitialScale(35);//设置缩放比例
        //webView.getSettings().setGeolocationEnabled(true);//启用地理定位

    }

    @SuppressLint("ClickableViewAccessibility")
    private void setWebViewListener() {
        // 左右滑动监听
        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        handler.sendEmptyMessage(MyApplication.HIDE_MENU);
                        posx = event.getX();
                        posy = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        curposx = event.getX();
                        curPosy = event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        float distancex = curposx - posx;
                        float distancey = curPosy - posy;
                        float distanceabsx = Math.abs(distancex);
                        float distanceabsy = Math.abs(distancey);
                        if (distanceabsx > distanceabsy) {
                            if (distanceabsx > 100) {
                                if (distancex > 0) {
                                    webView.goBack();
                                } else {
                                    webView.goForward();
                                }
                                return true;
                            }
                        } else {
                            if (distanceabsy > 40) {
                                if (distancey > 0) {
                                    handler.sendEmptyMessage(MyApplication.SHOW_TOOLBAR);
                                } else {
                                    handler.sendEmptyMessage(MyApplication.HIDE_TOOLBAR);
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }

        });

        webView.setWebChromeClient(new WebChromeClient() {
            //更新标题
            @Override
            public void onReceivedTitle(WebView view, String title) {
                currentTitle = title;
                currentUrl = view.getUrl();
                if (currentTitle != null && currentUrl != null) {
                    History history = new History(currentTitle, currentUrl);
                    DbUtil.insertIntoHistory(getContext(), history);
                }
                super.onReceivedTitle(view, title);
            }

            //更新加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    progressBar.setVisibility(View.INVISIBLE);//加载完网页进度条消失
                    nightMode(view);
                } else {
                    progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar.setProgress(newProgress);//设置进度值
                }
            }

        });

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //handler.proceed();//接受所有网站的证书,解决部分图片无法显示
            }

            //避免调用系统WebView
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                try {
                    if (url.startsWith("http")) {
                        // if (Build.VERSION.SDK_INT <= 26) {
                        webView.loadUrl(url);
                        return true;
                        //}
                    } else {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true;// 没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                //return false;
            }

            //加载错误
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                String s = error.getDescription().toString();
                if (s.equals("net::ERR_NAME_NOT_RESOLVED")) {
                    return;
                }

                Message m = handler.obtainMessage();
                m.obj = s;
                m.what = ERROR_WEBVIEW;
                handler.sendMessage(m);
                //webView.setVisibility(View.GONE);
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                startUrl = url;
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                currentTitle = view.getTitle();
                currentUrl = view.getUrl();
                super.onPageFinished(view, url);
            }

        });

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String s, String s1, String s2, String s3, long l) {
                try {
                    int index = s.indexOf("?");
                    if (index != -1) {
                        s = s.substring(0, index);
                    }
                    Message message = Message.obtain(handler, FILE_LENGTH, l);
                    message.sendToTarget();
                    DownloadThread downloadThread = new DownloadThread(s, getFileName(s), l, MyApplication.handler);
                    downloadThread.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void nightMode(WebView view) {
        if (MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_BLACK_THEME_FLAG) {
            view.loadUrl("javascript:(function() {" + "var parent = document.getElementsByTagName('head').item(0);" + "var style = document.createElement('style');" + "style.type = 'text/css';" + "style.innerHTML = window.atob('" + nightCode + "');" + "parent.appendChild(style)" + "})();");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

